package com.codc;


import com.struct.Request;
import com.struct.RequestHeader;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;

/**
 * Created by Administrator on 2016/1/7.
 */
public class RequestDecoder extends LengthFieldBasedFrameDecoder {

    public RequestDecoder(int maxFrameLength, int lengthFieldOffset, int lengthFieldLength) throws IOException {
        super(maxFrameLength, lengthFieldOffset, lengthFieldLength);

    }

    @Override
    protected Object decode(ChannelHandlerContext ctx, ByteBuf in)
            throws Exception {



        ByteBuf frame = (ByteBuf) super.decode(ctx, in);
        if (frame == null) {
            return null;
        }

        Request request = new Request();
        RequestHeader header = new RequestHeader();
        header.setCrcCode(frame.readInt());
        header.setLength(frame.readInt());
        header.setSessionID(frame.readLong());

        setUri(frame, request, header);

        if(StringUtils.isEmpty(header.getUri()))
           throw new Exception("uri is empty");

        if (frame.readableBytes() > 4) {
            byte[]  bodyBytes;
            int length = frame.readableBytes();
            bodyBytes = new byte[length];
            frame.getBytes(frame.readerIndex(), bodyBytes, 0 , length);

            request.setBodyBytes(bodyBytes);
        }
        else{
            request.setBody(frame.readByte());
        }

        System.out.println("serve receive request: " + request.toString());

        return request;
    }

    private void setUri(ByteBuf frame, Request request, RequestHeader header) {
        int uriLength = frame.readInt();
        byte[] uriByte = new byte[uriLength];
        frame.readBytes(uriByte);
        String uri = new String(uriByte);
        header.setUri(uri);

        request.setHeader(header);

    }
}
